/**
 * 首页模板编号3
 * @author  fubangfu2015@163.com
 * @data    2020/12/1
 * --------------------------------------
 */
import { addListener, removeListener, tip } from '../../../utils/common';
import util from '../../../utils/util';

const app = getApp();

Component({
  data : {
    meauLists : [],
    indicatorDots : true,
    autoplay : true,
    interval : 6000,
    duration : 800,
    swiperCurrent : 0,
    iphone : false,
    loadingHidden : false, // loading
    wxlogin : false,
    loadingMoreHidden : true,
    showSearch : false,
    showTitle : true,
    goods : [],
    //语言 - begin
    language : '',
    languages : [],
    langIndex : 0,
    //语言 - end
    // 货币
    currencys : [],
    currencyCodes : [],
    currencyIndex : 0,
    isHotActive : true,
    hotPage : 1,
    newPage : 1,
    newFinish : false,
    hotFinish : false,
    isTopData : []
  },
  // 被创建时
  created() {
    addListener('shop-index:onShow', this, this.onShow);
    addListener('shop-index:onReachBottom', this, this.onReachBottom);
  },
  attached() {
    // 此时触发事件，通知父页面发出事件执行onShow方法
    this.triggerEvent('ready');
  },
  //  移除时
  detached() {
    // 移除此组件上绑定的全局事件
    removeListener(this);
  },
  methods : {
    // 点击top文字
    clickTop(e) {
      let getlink = e.currentTarget.dataset.item.linkUrl;
      wx.navigateTo({
        url : (getlink[0] != '/' ? '/' : '') + getlink,
      });
    },
    changeStatus(e) {
      let type = e.currentTarget.dataset.type, istop = type == 'top';
      this.setData({
        isHotActive : istop
      });
      if (istop) {
        this.setData({
          goods : this.data.hot_products
        });
      } else {
        let isTopData = this.data.isTopData;
        if (isTopData && isTopData.length > 0) {
          this.setData({
            goods : isTopData
          });
        } else {
          this.getNewSaleLists();
        }
      }
    },
    onShow(promise) {
      this.setData({
        isTopData : [],
        page : 1,
        hotPage : 1,
        newPage : 1,
        hot_products : []
      });

      // ajax请求
      this.loadHomeData(promise);
      //获取购物车商品数量
      // app.getShopCartNum();
      // 添加店铺浏览记录
      // util.storeBrower(app);
    },
    getNewSaleLists() {
      var that = this;
      //4个热销广告位
      wx.request({
        url : app.globalData.urls + '/product/new-list',
        header : app.getRequestHeader(),
        method : 'POST',
        data : {
          page : this.data.newPage,
          bdmin_user_id : util.share_bdmin_user_id()
        },
        success : function (res) {
          if (res.data.code == 200) {
            let data = res.data.data;
            if (data.length == 0) {
              that.setData({
                newFinish : true
              });
            } else {
              let isTopData = that.data.isTopData.concat(data);
              that.setData({
                goods : isTopData,
                isTopData : isTopData
              });
            }
          } else {
            that.setData({
              goods : []
            });
          }

        }
      });
    },
    // 语言
    changeLanguage(e) {
      let index = e.detail.value;
      // 设置当前的Picker的LangIndex
      this.setData({	// (1)
        langIndex : index
      });
      // 设置Locale
      wx.T.setLocaleByIndex(index);
      // 设置language变量（翻译Object）
      this.setLanguage();

      // 写入Storage
      var fecshop_lang = wx.T.getCodeByIndex(index);
      wx.setStorageSync('fecshop-lang', fecshop_lang);
      // 添加事件
      event.emit('languageChanged');
      this.loadHomeData();
    },
    // 语言
    // 设置language变量（翻译Object）
    setLanguage() {
      this.setData({
        language : wx.T.getLanguage()
      });
    },
    loadHomeData(promise) {
      promise.then(data => {
        this.setData({
          title : data.store_name,
          goods : data.hot_products,
          hot_products : data.hot_products,
          banners : data.banners,
          meauLists : data.top,
          category : data.category
        });
      });
    },
    loadHomeData1() {
      var that = this;
      //4个热销广告位
      wx.request({
        url : app.globalData.urls + '/index/index',///wx/home/index
        header : app.getRequestHeader(),
        method : 'POST',
        data : {
          bdmin_user_id : util.share_bdmin_user_id()
        },
        success : function (res) {
          if (res.data.code == 200) {
            // that.setData({
            //   hot: res.data.data.hot
            // });
            // if (res.data.data.topgoods) {
            // that.setData({
            //   topgoods: res.data.data.topgoods
            // });
            let data = res.data.data;
            wx.setStorageSync('store_name', data.store_name);
            that.setData({
              title : data.store_name,
              goods : data.hot_products,
              hot_products : data.hot_products,
              banners : data.banners,
              meauLists : data.top,
              category : data.category
            });
            // }
            // that.setData({
            //   banners: res.data.data.banners
            // });
            // 货币
            // that.initCurrency(res.data.data.currency)

            app.saveReponseHeader(res);
          }
        }
      });
    },
    // 货币
    getCurrencyIndex(currencyCodeList, currentCurrency) {
      for (var x in currencyCodeList) {
        if (currencyCodeList[x] == currentCurrency) {
          return x;
        }
      }
    },
    // 货币
    initCurrency(currencyObj) {
      var that = this;
      var currencyCodeList = currencyObj.currencyCodeList;  // ["EUR", "USD", "GBP", "CNY"]
      var currencyList = currencyObj.currencyList;  // ["€ EUR", "$ USD", "£ GBP", "￥ CNY"]
      var currentCurrency = currencyObj.currentCurrency;  // "CNY"
      var currencyIndex = that.getCurrencyIndex(currencyCodeList, currentCurrency);
      that.setData({
        currencys : currencyList
      });
      that.setData({
        currencyCodes : currencyCodeList
      });
      that.setData({
        currencyIndex : currencyIndex
      });
    },
    // 货币  - 更改货币
    changeCurrency(e) {
      let index = e.detail.value;
      // 设置当前的Picker的LangIndex
      this.setData({	// (1)
        currencyIndex : index
      });
      // 添加事件
      event.emit('currencyChanged');
      // 写入Storage
      var currencyCodes = this.data.currencyCodes;
      var fecshop_currency = currencyCodes[index];
      wx.setStorageSync('fecshop-currency', fecshop_currency);
      this.loadHomeData();
    },
    _onLoad(e) {
      // 带上这个数据
      if (e.getBdmin_user_id) {
        util.clearLogin(e.getBdmin_user_id);
      }
      // 分享进来的
      if (e.share == 1) {
        util.stat(app, 'pages/index/index', 2);
      } else {
        util.stat(app, 'pages/index/index', 1);
      }
      wx.stopPullDownRefresh();
      var that = this;
      // 语言
      // 设置picker的语言选项
      that.setData({
        languages : wx.T.getLangNames()
      });
      // 设置picker的语言选项中当前的langIndex
      that.setData({
        'langIndex' : wx.T.langIndex
      });
      // 设置当前页面的language变量 - 每个页面都要有
      this.setLanguage();
      // 设置当前页面的language Index - 每个页面都要有
      wx.T.setLocaleByIndex(wx.T.langIndex);
      // 语言 - 结束
      // 头部
      wx.setNavigationBarColor({
        frontColor : '#000000',
        backgroundColor : '#ffffff'
      });
      app.fadeInOut(this, 'fadeAni', 1);
      if (app.globalData.iphone == true) {
        that.setData({
          iphone : true
        });
      }

    },
    swiperchange(e) {
      this.setData({
        swiperCurrent : e.detail.current
      });
    },
    toDetailsTap(e) {
      wx.navigateTo({
        url : '/pages/goods-detail/goods-detail?id=' + e.currentTarget.dataset.id
      });
    },
    tapBanner(e) {
      // console.log()
      wx.navigateTo({
        url : e.currentTarget.dataset.id
      });
      // if (e.currentTarget.dataset.id != 0) {
      //   "/pages/goods-detail/goods-detail?id=" + e.currentTarget.dataset.id
      // }
    },
    tapSales(e) {
      if (e.currentTarget.dataset.id != 0) {
        wx.navigateTo({
          url : e.currentTarget.dataset.id
        });
      }
    },
    userlogin(e) {

      // var that = this;
      // var iv = e.detail.iv, detail = e.detail.userInfo;
      // var encryptedData = e.detail.encryptedData;
      // wx.login({
      //   success: function (wxs) {
      //     console.log("wxs","页面",wxs)
      //     wx.request({
      //       url: app.globalData.urls + '/order/update',///user/wxapp/register/complex
      //       data: {
      //         customer_id: detail,
      //         nickName: detail.nickName,
      //         avatarUrl: detail.avatarUrl
      //       },
      //       success: function (res) {
      //         if (res.data.code != 0) {
      //           wx.showModal({
      //             title: '温馨提示',
      //             content: '需要您的授权，才能正常使用哦～',
      //             showCancel: false,
      //             success: function (res) { }
      //           })
      //         } else {
      //           console.log(res.detail.userInfo)
      //           that.setData({ wxlogin: true })
      //           app.login();
      //           wx.showToast({
      //             title: '授权成功',
      //             duration: 2000
      //           })
      //           app.globalData.usinfo = 1;
      //           wx.showTabBar();
      //         }
      //       }
      //     })
      //   }
      // })
    },
    onPageScroll(t) {
      // if(t.scrollTop >= 180){
      // 	wx.setNavigationBarColor({
      // 		frontColor: '#000000',
      // 		backgroundColor: '#ffffff'
      // 	})
      // 	app.fadeInOut(this,'fadeAni',1)
      // }else{
      // 	wx.setNavigationBarColor({
      // 		frontColor: '#ffffff',
      // 		backgroundColor: '#ffffff'
      // 	})
      // 	app.fadeInOut(this,'fadeAni',0)
      // }
    },
    getHot() { // 获取热卖列表
      var that = this;
      //4个热销广告位
      wx.request({
        url : app.globalData.urls + '/product/hot-list',
        header : app.getRequestHeader(),
        method : 'POST',
        data : {
          page : this.data.hotPage,
          bdmin_user_id : util.share_bdmin_user_id()
        },
        success : function (res) {
          if (res.data.code == 200) {
            let data = res.data.data;
            if (data.length == 0) {
              that.setData({
                hotFinish : true
              });
            } else {
              let goods = that.data.goods.concat(data);
              that.setData({
                goods : goods,
                hot_products : goods
              });
            }
          }

        }
      });
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
      // hotFinish  热卖结束
      // newFinish 新品结束
      if (this.data.isHotActive) {
        if (!this.data.hotFinish) {
          this.setData({
            hotPage : this.data.hotPage + 1
          });
          this.getHot();
        }
      } else {
        if (!this.data.newFinish) {
          this.setData({
            newPage : this.data.newPage + 1
          });
          this.getNewSaleLists();
        }
      }
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
      this.onLoad();
    },
    onShareAppMessage() {
      return {
        // title: '天天精选',
        title : '我在天天精选挑选这些好物，快来查看吧',
        // imageUrl: '',  //用户分享出去的自定义图片大小为5:4,
        path : '/pages/index/index?share=1&getBdmin_user_id=' + util.share_bdmin_user_id(),
        success : function (res) {
          // 转发成功
          wx.showToast({
            title : '邀请成功',
            icon : 'success',
            duration : 2000
          });
        },
        fail : function (res) {
          // 分享失败
          wx.showToast({
            title : '邀请失败',
            icon : 'error',
          });
        },
      };
    },
  }
});
